import axios from "axios";
import {
    ElMessage,
    ElMessageBox
} from "element-plus";

axios.defaults.timeout = 12000;

//axios 队列cache
const pendingArr = [];
const stopRepeatRequest = function (reqList, url, cancel, errorMessage) {
    const errorMsg = errorMessage || ''
    for (let i = 0; i < reqList.length; i++) {
        if (reqList[i] === url) {
            cancel(errorMsg)
            return
        }
    }
    reqList.push(url)
}

/**
 * 允许某个请求可以继续进行
 * @param {array} reqList 全部请求列表
 * @param {string} url 请求地址
 */
const allowRequest = function (reqList, url) {
    for (let i = 0; i < reqList.length; i++) {
        if (reqList[i] === url) {
            reqList.splice(i, 1)
            break
        }
    }
}
axios.interceptors.request.use(
    (config)=>{
                let cancel
                // 设置cancelToken对象
                config.cancelToken = new axios.CancelToken(function(c) {
                    cancel = c
                })
                // 可以在这里设置请求头
                //     let authorization = store.state.common.info.access_token;
                //     if (authorization) {
                //         config.headers.Authorization = "bearer " + authorization
                //     }
                //     if (autoInfo) {
                //         config.headers['Auto-key'] = autoInfo.value
                //     }
                // 阻止重复请求。当上个请求未完成时，相同的请求不会进行
                stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`)
                return config
            },
            err => Promise.reject(err)
)
axios.interceptors.response.use(
    response => {
        // 增加延迟，相同请求不得在短时间内重复发送
        setTimeout(() => {
            allowRequest(pendingArr, response.config.url)
        }, 1000)
        // ...请求成功后的后续操作


        // successHandler(response)
    },
    error => {
        if (axios.isCancel(thrown)) console.log(thrown.message); else {
            // 增加延迟，相同请求不得在短时间内重复发送
            setTimeout(() => {
                allowRequest(pendingArr, error.config.url)
            }, 1000)
        }
        // ...请求失败后的后续操作


        // errorHandler(error)
    }
)